package com.lemon.boot.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lemon.boot.common.enums.DeleteEnum;
import com.lemon.boot.common.enums.StatusEnum;
import com.lemon.boot.common.enums.TimeEnum;
import com.lemon.boot.common.utils.JwtUtil;
import com.lemon.boot.common.utils.SecurityUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * @author 李猛
 * @datetime 2023/4/15 10:49
 * @description 类对象
 */
@Component
public class MybatisPlusObjectHandler implements MetaObjectHandler {
    /**
     * 新增时的自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (StringUtils.hasText(metaObject.findProperty(StatusEnum.ENABLE.getColumn(), false))) {
            this.setFieldValByName(StatusEnum.ENABLE.getColumn(), StatusEnum.ENABLE.getStatus(), metaObject);
        }
        if (StringUtils.hasText(metaObject.findProperty(TimeEnum.CREATE.getProperty(), true))) {
            this.setFieldValByName(TimeEnum.CREATE.getProperty(), LocalDateTime.now(), metaObject);
        }

        //是否是认证用户
        boolean isAuthenticated = SecurityUtil.getAuthentication().isAuthenticated();
        if (isAuthenticated && StringUtils.hasText(metaObject.findProperty("createBy", true))) {
            this.setFieldValByName("createBy", JwtUtil.getCurrentUser().getName(), metaObject);
        }
    }

    /**
     * 修改时的自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (StringUtils.hasText(metaObject.findProperty(TimeEnum.UPDATE.getProperty(), true))) {
            this.setFieldValByName(TimeEnum.UPDATE.getProperty(), LocalDateTime.now(), metaObject);
        }

        //是否是认证用户
        boolean isAuthenticated = SecurityUtil.getAuthentication().isAuthenticated();
        if (isAuthenticated && StringUtils.hasText(metaObject.findProperty("updateBy", true))) {
            this.setFieldValByName("updateBy", JwtUtil.getCurrentUser().getName(), metaObject);
        }
    }
}
